#! /usr/bin/env pythonoutmasages
# -*- coding: utf-8 -*-
 
import threading
import os
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
import time
from tkinter import *
import copy
from ble_btooth import *
from buttHandle import *
from tkinter import messagebox
from imageHandle import *
from converter import *
from check import *
import requests
import json
from lb_log import *

# import logging
# #logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
# #                    level=logging.DEBUG)

# lb_logger = logging.getLogger('light_box')
# lb_logger.setLevel(logging.DEBUG)
# lb_formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

# lb_file_handler = logging.FileHandler('light_box_test.log', encoding="utf-8", mode="a")
# lb_file_handler.setLevel(level=logging.INFO)
# lb_file_handler.setFormatter(lb_formatter)

# lb_stream_handler = logging.StreamHandler()
# lb_stream_handler.setLevel(logging.DEBUG)
# lb_stream_handler.setFormatter(lb_formatter)

# lb_logger.addHandler(lb_file_handler)
# lb_logger.addHandler(lb_stream_handler)

lb_logger.debug('debug级别，一般用来打印一些调试信息，级别最低')
# lb_logger.info('info级别，一般用来打印一些正常的操作信息')
# lb_logger.warning('waring级别，一般用来打印警告信息')
# lb_logger.error('error级别，一般用来打印一些错误信息')
# lb_logger.critical('critical级别，一般用来打印一些致命的错误信息，等级最高')
lb_logger.info('程序启动')


Information_Window = scrolledtext

randomV = 000000
global outmessages
handleFlag = False
bleConnected = False
END_CHECK_FLAG = False

Connection_Id = 2000
Connection_Id_chip = 1234

SN_LEN = 13

ACTIVE_NONE = 0
ACTIVE_RED_BUTTON = 1
ACTIVE_GREEN_BUTTON =2
ACTIVE_BLUE_BUTTON =3
ACTIVE_ALL_CLOSE_BUTTON = 4
ACTIVE_ON_BUTTON = 5
ACTIVE_OFF_BUTTON = 6
ACTIVE_GET_SN_BUTTON = 7
ACTIVE_BINDING_SN_BUTTON = 8
ACTIVE_GET_RANDOM_BUTTON = 9
ACTIVE_BINDING_RANDOM_BUTTON = 10

buttonActive = ACTIVE_NONE

R_CALI_VALUE = (253, 40, 1)
G_CALI_VALUE = (1, 220, 115)
B_CALI_VALUE = (1, 40, 254)
#W_CALI_VALUE = (180, 210, 210)
W_CALI_VALUE = (129, 120, 120)
BK_CALI_VALUE = (0, 0, 0)
CALI_OFFSET_VALUE = 50

testitem = [{"name":"红光","cmd":"red", "result": "NULL"},
            {"name":"绿光","cmd":"green", "result": "NULL"},
            {"name":"蓝光","cmd":"blue", "result": "NULL"},
            {"name":"灯板关闭","cmd":"black", "result": "NULL"},
            {"name":"灯带打开","cmd":"on", "result": "NULL"},
            {"name":"灯带关闭","cmd":"off", "result": "NULL"}]

sn_rand_pair = {"LB1A308010001": "106934", "LB1A308010002": "313090", "LB1A308010003": "136538", "LB1A308010004": "700615", "LB1A308010005": "045080",
                "LB1A308020001": "691119", "LB1A308020002": "872628", "LB1A308020003": "532308", "LB1A308020004": "218957", "LB1A308020005": "050675",
                "LB1A308030001": "093864", "LB1A308030002": "823104", "LB1A308030003": "398122", "LB1A308030004": "804990", "LB1A308030005": "640019",
                "LB1A308040001": "751096", "LB1A308040002": "648739", "LB1A308040003": "836082", "LB1A308040004": "745459", "LB1A308040005": "253942",
                "LB1A308050001": "375598", "LB1A308050002": "439892", "LB1A308050003": "058819", "LB1A308050004": "508942", "LB1A308050005": "701983",
                "LB1A308060001": "821037", "LB1A308060002": "239454", "LB1A308060003": "282747", "LB1A308060004": "135920", "LB1A308060005": "175868",
                "LB2A411110001": "780669", "LB2A411110002": "214906", "LB2A411110003": "110071", "LB2A411110004": "661065", "LB2A411110005": "455286",
                "LB2A411120001": "656651", "LB2A411120002": "491545", "LB2A411120003": "329994", "LB2A411120004": "262239", "LB2A411120005": "565356",
                "LB2A411130001": "340577", "LB2A411130002": "010066", "LB2A411130003": "048625", "LB2A411130004": "183917", "LB2A411130005": "349290",
                "LB2A411140001": "353534", "LB2A411140002": "562548", "LB2A411140003": "014948", "LB2A411140004": "026795", "LB2A411140005": "835084",
                "LB2A411150001": "902326", "LB2A411150002": "823641", "LB2A411150003": "009902", "LB2A411150004": "547243"
                }

upload_url = 'https://api.meican.com/v2.1/closet/addTestResult2?client_id=dlSCQvxvs1ZQyL52E6nXdoNLcNjL8s0&client_secret=mOlv94q1p5yo8lHiJU5g17ESGK0JmZU'
websitecookies = {"Cookies" : "guestId=7df2d692-a603-4b6c-a39b-a41057bd74d9; machineId=5151f955-5c5c-4c5f-8b8f-cc1478478617"}
#find_rand_url = "https://devices-api.meican.com/device/sn/queryDevice?type=lightbox&sn="
find_rand_url = "https://devices-api.meican.com/sn/query?sn="

rand_headers = {
  'x-mc-image': 'feature-closet-snackbar',
  'Cookie': 'AWSALB=Yqb3F0NTIY0MF/SJdY7jktFpKaLc9J0S9HzDGa94OGrBUSwIAfOZvJROyNm4jTwLO26Xuf3dBdWhh2nfCRZ7ZU670LgkvGi1O3IUkha6I/2c5NBCRRJVwSm+kFJo; AWSALBCORS=Yqb3F0NTIY0MF/SJdY7jktFpKaLc9J0S9HzDGa94OGrBUSwIAfOZvJROyNm4jTwLO26Xuf3dBdWhh2nfCRZ7ZU670LgkvGi1O3IUkha6I/2c5NBCRRJVwSm+kFJo'
}

rand_payload = {}

result_header = {
    "uniqueId": 1626856952766,
    "data": [
    ],
    "type": "finalresult"
}

single_result_template = {
            "type": "result",
            "result": "1",
            "raw": {
                "connectionId": 2022,
                "data": {},
                "resultCode": "OK", 
                "resultDescription": ""
            },
            "state": "endtest",
            "testcase": {
                "name": "上电",
                "lowThreshold": "1.0",
                "highThreshold": "1.0",
                "timeout": "55000",
                "command": "power_on"
            } 
        }

test_headers = {
    'Content-Type': 'application/json'
}



cmd_ok = "success"
cmd_fail = "failed"
PRODUCT_RE_PATH = "./product_re"

# outmessages = CamaroCap() 

def save_result(result_file, final_result):
    #jsonfile = result_name + ".json"
    final_result = result_header

    with open(result_file, "w", encoding='utf-8') as resultfile:
        json.dump(final_result, resultfile, indent=4, ensure_ascii=False)
    resultfile.close()
    print("the result", result_file, "is saved!")

def upload_result(sn):

    if sn:
        # print(sn)
        # if sn_rand_pair.get(sn):
        #     random = sn_rand_pair[sn]
        # else:
        #     messagebox.showerror("错误提示", "SN不存在！！")
        #     return False
        #random = sn_rand_pair[sn]
        final_result = copy.deepcopy(result_header)
        filename = PRODUCT_RE_PATH + "/" + sn + ".json"
        #filename = sn + ".json"
        # with open(filename, 'r', encoding='utf8') as fp:
        #     json_data = json.load(fp)
        # lb_logger.info("this is json", json_data)
        # print('这是读取到文件数据的数据类型：', type(json_data)) 
        # test_result = json.dumps(json_data)
        # print('这是读取到文件数据的数据类型：', type(test_result))
        #test_result = {}
        Connection_Id = Connection_Id_chip
        single_result_in_dict = single_result_template 
        # for rkey in testresult.items():
        #     test_result[rkey[0]] = rkey[1]
        for i in range(len(testitem)):
            single_result_in_dict["testcase"]["name"] = testitem[i]["name"]
            single_result_in_dict["testcase"]["command"] = testitem[i]["cmd"]
            single_result_in_dict["raw"]["resultCode"] = testitem[i]["result"]
            print("test result", testitem[i]["result"])
            single_result_in_dict["raw"]["connectionId"] = Connection_Id
            result_append = copy.deepcopy(single_result_in_dict)
            final_result["data"].append(result_append)
        final_result["uniqueId"] = int(time.time())
        save_result(filename, final_result)
        print("测试结果:", final_result)

        resultdata = {   
            "content" : json.dumps(final_result),
            "sn" : sn,
            "closetTestItemId" : "36",
            "sn2" : randomV
        }
        try:
            response = requests.post(upload_url, headers=websitecookies, data=resultdata, timeout=(50, 50))
            json_result = response.json()
            print(json_result)
            if json_result['resultDescription'] == "SUCCESS":
                messagebox.showinfo(title = "上传提示", message = "上传成功")
                return 0
            else:
                return 1
        except requests.exceptions.RequestException as emsg:
            print("命令发送错误或超时！", emsg)
            messagebox.showwarning(title = "测试提示", message = "上传结果失败，提示：" + str(emsg))
            return 1
    else:
        messagebox.showwarning(title = "weapons", message = "SN未输入")


def checkStart():
    global handleFlag
    global thread2
    global outmessages
    outmessages = CameraCap()
    if handleFlag == False:
        handleFlag = True

        Information_Window.insert("end", '开始连接MC-蓝牙设备\n')       # 在操作信息窗口显示发送的指令并换行，end为在窗口末尾处显示
        Information_Window.see("end")         # 此处为显示操作信息窗口进度条末尾内容，以上两行可实现窗口内容满时，进度条自动下滚并在最下方显示新的内容

        # thread1.setDaemon(True)# 守护线程
        thread1 = threading.Thread(target = activeBlueth, daemon = True)
        thread1.start()

def checkEnd():
    global END_CHECK_FLAG 
    global bleConnected
    global snVar
    global randomVar
    global Receive_Window
    global outmessages
    del outmessages

    snVar.delete(0, 'end')
    #randomVar.delete(0, 'end')
    Receive_Window.delete(1.0, END)
    if bleConnected:
        Information_Window.insert("end", '停止检测\n')       # 在操作信息窗口显示发送的指令并换行，end为在窗口末尾处显示
        Information_Window.see("end")         # 此处为显示操作信息窗口进度条末尾内容，以上两行可实现窗口内容满时，进度条自动下滚并在最下方显示新的内容

        END_CHECK_FLAG = True

        global cmdQue
        if cmdQue.empty():
            cmdQue.put(EXIT_THREAD_CMD)

def checkRGB(col):
    rVal = 255
    gVal = 255
    bVal = 255
    with open('./RGBparams.json', 'r', encoding='utf-8') as f:
        RGB = json.load(f)
    #print(RGB)
    offset_value = 100
    if col == 'RED':
        print('检测红色')
        lb_logger.info('start red checking')
        rVal = RGB["RGBstandard"]["R_CALI_VALUE"]["R_V"]
        gVal = RGB["RGBstandard"]["R_CALI_VALUE"]["G_V"]
        bVal = RGB["RGBstandard"]["R_CALI_VALUE"]["B_V"]
        offset_value = RGB["RGBoffset"]
    elif col == 'GREEN':
        print('检测绿色')
        lb_logger.info('start green checking')
        rVal = RGB["RGBstandard"]["G_CALI_VALUE"]["R_V"]
        gVal = RGB["RGBstandard"]["G_CALI_VALUE"]["G_V"]
        bVal = RGB["RGBstandard"]["G_CALI_VALUE"]["B_V"]
        offset_value = RGB["RGBoffset"]
    elif col == 'BLUE':
        print('检测蓝色')
        lb_logger.info('start blue checking')
        rVal = RGB["RGBstandard"]["B_CALI_VALUE"]["R_V"]
        gVal = RGB["RGBstandard"]["B_CALI_VALUE"]["G_V"]
        bVal = RGB["RGBstandard"]["B_CALI_VALUE"]["B_V"]
        offset_value = RGB["RGBoffset"]
    elif col == 'WHITE':
        print('检测白色')
        lb_logger.info('start white checking')
        rVal = RGB["RGBstandard"]["W_CALI_VALUE"]["R_V"]
        gVal = RGB["RGBstandard"]["W_CALI_VALUE"]["G_V"]
        bVal = RGB["RGBstandard"]["W_CALI_VALUE"]["B_V"]
        offset_value = RGB["WHITEoffset"]
    elif col == 'BLACK':
        print('检测黑色')
        lb_logger.info('start black checking')
        rVal = RGB["RGBstandard"]["BK_CALI_VALUE"]["R_V"]
        gVal = RGB["RGBstandard"]["BK_CALI_VALUE"]["G_V"]
        bVal = RGB["RGBstandard"]["BK_CALI_VALUE"]["B_V"]
        offset_value = RGB["RGBoffset"]
    
    #offset_value = RGB["RGBoffset"]
    image = outmessages.Camera_image(0)
    image = outmessages.Camera_image(0) # 调用摄像头
    print(image)
    imgCopyList = processingRawImage(image)
    # print("copy=",imgCopyList)
    if col == 'GREEN':
        for v in imgCopyList:
            # print(v)
            resR,resG,resB = mean_rgb(v, 0, 0, 100, 100)
            if (resR < 20) and (resG >= 200) and (resB < 120):
                lb_logger.info("check pass in : %s and rgb value is: %d  %d  %d", col, resR, resG, resB)
                print('check pass')
            else:
                print("check failed")
                lb_logger.info("check failed!!!!!! in : %s and rgb value is: %d  %d  %d", col, resR, resG, resB)
                return False
    else:
        for v in imgCopyList:
            # print(v)
            resR,resG,resB = mean_rgb(v, 0, 0, 100, 100)
            if abs(resR - rVal) <= offset_value and abs(resG - gVal) <= offset_value and abs(resB - bVal) <= offset_value:
                lb_logger.info("check pass in : %s and rgb value is: %d  %d  %d", col, resR, resG, resB)
                print('check pass')
            else:
                print("check failed")
                lb_logger.info("check failed!!!!!! in : %s and rgb value is: %d  %d  %d", col, resR, resG, resB)
                return False
    return True

def handleBleAck(ackData):
    print("ackData=", ackData)
    if ackData[3] == 0x01:
        time.sleep(1)
        checkImageRGB(image)

def handleBleData():
    global bleConnected
    global cmdQue
    global buttonActive
    global handleFlag
    global END_CHECK_FLAG
    global Receive_Window
    bleConnected = False

    while True:
        if not bleConnStaQue.empty():
            sta = bleConnStaQue.get()
            print('bleConnSta=', sta)

            if sta == BLE_CONNECT_OK:
                bleConnected = True
                Information_Window.insert("end", '蓝牙设备连接成功\n')       # 在操作信息窗口显示发送的指令并换行，end为在窗口末尾处显示
                Information_Window.see("end")         # 此处为显示操作信息窗口进度条末尾内容，以上两行可实现窗口内容满时，进度条自动下滚并在最下方显示新的内容
            else:
                handleFlag = False
                bleConnected = False
                Information_Window.insert("end", '蓝牙设备连接失败\n')       # 在操作信息窗口显示发送的指令并换行，end为在窗口末尾处显示
                Information_Window.see("end")         # 此处为显示操作信息窗口进度条末尾内容，以上两行可实现窗口内容满时，进度条自动下滚并在最下方显示新的内容

        if END_CHECK_FLAG:
            while disConnQue.empty():
                time.sleep(1)
            disConnQue.get()
            END_CHECK_FLAG = False
            handleFlag = False
            bleConnected = False

        if cmdQue.empty():
            if buttonActive == ACTIVE_RED_BUTTON:
                cmdQue.put(CHECK_RED_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                # print("rxData=", rxData)
                if rxData[3] == 0x01:
                    time.sleep(2)
                    res = checkRGB('RED')
                    # if messagebox.askyesno("提示", "红光测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[0]["result"] = "OK"
                    #     Receive_Window.insert('end', "红光测试成功\n")
                    # else:
                    #     print("测试失败！！")
                    #     testitem[0]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "红光测试失败\n")   
                    if res:
                        messagebox.showinfo('提示', '红色测试通过')
                        testitem[0]["result"] = "OK"
                        Receive_Window.insert('end', "红光测试成功\n")
                    else:
                        messagebox.showinfo('提示', '红色测试失败')
                        testitem[0]["result"] = "FAIL"
                        Receive_Window.insert('end', "红光测试失败\n")
                buttonActive = ACTIVE_GREEN_BUTTON
                #print("我被执行了", buttonActive)
            elif buttonActive == ACTIVE_GREEN_BUTTON:
                cmdQue.put(CHECK_GREEN_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    time.sleep(2)
                    # if messagebox.askyesno("提示", "绿光测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[1]["result"] = "OK"
                    #     Receive_Window.insert('end', "绿光测试成功\n") 
                    # else:
                    #     print("测试失败！！")
                    #     testitem[1]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "绿光测试失败\n")                 
                    res = checkRGB('GREEN')
                    if res:
                        messagebox.showinfo('提示', '绿色测试通过')
                        testitem[1]["result"] = "OK"
                        Receive_Window.insert('end', "绿光测试成功\n") 
                    else:
                        messagebox.showinfo('提示', '绿色测试失败')
                        testitem[1]["result"] = "FAIL"
                        Receive_Window.insert('end', "绿光测试失败\n")  
                buttonActive = ACTIVE_BLUE_BUTTON
            elif buttonActive == ACTIVE_BLUE_BUTTON:
                cmdQue.put(CHECK_BLUE_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    time.sleep(2)
                    # if messagebox.askyesno("提示", "蓝光测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[2]["result"] = "OK"
                    #     Receive_Window.insert('end', "蓝光测试成功\n") 
                    # else:
                    #     print("测试失败！！")
                    #     testitem[2]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "蓝光测试失败\n") 
                    res = checkRGB('BLUE')
                    if res:
                        messagebox.showinfo('提示', '蓝色测试通过')
                        testitem[2]["result"] = "OK"
                        Receive_Window.insert('end', "蓝光测试成功\n") 
                    else:
                        messagebox.showinfo('提示', '蓝色测试失败')
                        testitem[2]["result"] = "FAIL"
                        Receive_Window.insert('end', "蓝光测试失败\n") 
                buttonActive = ACTIVE_ALL_CLOSE_BUTTON
            elif buttonActive == ACTIVE_ALL_CLOSE_BUTTON:
                cmdQue.put(CHECK_CLOSE_ALL_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    time.sleep(2)
                    res = checkRGB('BLACK')
                    if res:
                        messagebox.showinfo('提示', 'RGB关闭成功')
                        print("测试通过！！")
                        testitem[3]["result"] = "OK"
                        Receive_Window.insert('end', "灯板关闭测试成功\n")
                    else:
                        print("测试失败！！")
                        testitem[3]["result"] = "FAIL"
                        Receive_Window.insert('end', "灯板关闭测试失败\n") 
                        messagebox.showinfo('提示', 'RGB关闭失败')
                    # if messagebox.askyesno("提示", "灯板关闭测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[3]["result"] = "OK"
                    #     Receive_Window.insert('end', "灯板关闭测试成功\n") 
                    # else:
                    #     print("测试失败！！")
                    #     testitem[3]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "灯板关闭测试失败\n") 
                buttonActive = ACTIVE_ON_BUTTON
            elif buttonActive == ACTIVE_ON_BUTTON:
                cmdQue.put(CHECK_WHITE_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    time.sleep(2)
                    # if messagebox.askyesno("提示", "灯条开测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[4]["result"] = "OK"
                    #     Receive_Window.insert('end', "灯条开启测试成功\n") 
                    # else:
                    #     print("测试失败！！")
                    #     testitem[4]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "灯条开启测试失败\n") 
                    res = checkRGB('WHITE')
                    if res:
                        messagebox.showinfo('提示', '白色测试通过')
                        testitem[4]["result"] = "OK"
                        Receive_Window.insert('end', "灯条开启测试成功\n") 
                    else:
                        messagebox.showinfo('提示', '白色测试失败')
                        testitem[4]["result"] = "FAIL"
                        Receive_Window.insert('end', "灯条开启测试失败\n")
                    buttonActive = ACTIVE_OFF_BUTTON
            elif buttonActive == ACTIVE_OFF_BUTTON:
                cmdQue.put(CHECK_OFF_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    time.sleep(2)
                    res = checkRGB('BLACK')
                    if res:
                        messagebox.showinfo('提示', 'LED关闭成功')
                        testitem[5]["result"] = "OK"
                        Receive_Window.insert('end', "灯条关闭测试成功\n") 
                    else:
                        messagebox.showinfo('提示', 'LED关闭失败')
                        testitem[5]["result"] = "FAIL"
                        Receive_Window.insert('end', "灯条关闭测试失败\n")
                    # if messagebox.askyesno("提示", "灯条关测试是否通过？？"):
                    #     print("测试通过！！")
                    #     testitem[5]["result"] = "OK"
                    #     Receive_Window.insert('end', "灯条关闭测试成功\n") 
                    # else:
                    #     print("测试失败！！")
                    #     testitem[5]["result"] = "FAIL"
                    #     Receive_Window.insert('end', "灯条关闭测试失败\n") 

                buttonActive = ACTIVE_NONE
                Receive_Window.insert('end', "测试结束\n")
                print("testitemnow is:  ", testitem)
            elif buttonActive == ACTIVE_GET_SN_BUTTON:
                cmdQue.put(GET_SN_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    char_list = []
                    # char_list2 = []
                    sn = 'SN:'
                    # random = 'random:'
                    for i in range(4, 17):
                        # print('assic:', chr(rxData[i]))
                        char_list.append(chr(rxData[i]))
                    # print('char_list=',char_list)
                    # for i in range(18, 24):
                    #     char_list2.append(chr(rxData[i]))
                    for v in char_list:
                        sn = sn + str(v)
                    # for v in char_list2:
                    #     random = random + str(v)
                    # sn = sn + random
                    messagebox.showinfo('提示',  sn)
                else:
                    messagebox.showinfo('提示', 'SN获取失败')
                buttonActive = ACTIVE_NONE
            elif buttonActive == ACTIVE_GET_RANDOM_BUTTON:
                cmdQue.put(GET_RANDOM_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    char_list = []
                    # char_list2 = []
                    rand = 'RANDOM:'
                    # random = 'random:'
                    for i in range(4, 10):
                        # print('assic:', chr(rxData[i]))
                        char_list.append(chr(rxData[i]))
                    # print('char_list=',char_list)
                    # for i in range(18, 24):
                    #     char_list2.append(chr(rxData[i]))
                    for v in char_list:
                        rand = rand + str(v)
                    # for v in char_list2:
                    #     random = random + str(v)
                    # sn = sn + random
                    messagebox.showinfo('提示',  rand)
                else:
                    messagebox.showinfo('提示', 'RANDOM获取失败')
                buttonActive = ACTIVE_NONE
            elif buttonActive == ACTIVE_BINDING_SN_BUTTON:
                cmdQue.put(BIND_SN_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    messagebox.showinfo('提示',  'SN绑定成功')
                    #snVar.delete(0, 'end')
                    #randomVar.delete(0, 'end')
                else:
                    messagebox.showinfo('提示', 'SN绑定失败')
                buttonActive = ACTIVE_NONE
            elif buttonActive == ACTIVE_BINDING_RANDOM_BUTTON:
                cmdQue.put(BIND_SN_CMD)
                while bleRxDataQue.empty():
                    time.sleep(0.1)
                rxData = bleRxDataQue.get()
                if rxData[3] == 0x01:
                    messagebox.showinfo('提示',  'RANDOM绑定成功')
                    #snVar.delete(0, 'end')
                    #randomVar.delete(0, 'end')
                else:
                    messagebox.showinfo('提示', 'RANDOM绑定失败')
                buttonActive = ACTIVE_NONE
        #buttonActive = ACTIVE_NONE

        time.sleep(0.1)
    

class GUI:        
    global thread2
    def __init__(self):
        width = 780
        height = 530
        # self.root = tk.Tk()

        #定义父容器
        self.root = tk.Tk()               # 父容器
        self.root.title("Bluetooth Test Tool")  # 父容器标题
        # GUI.geometry("800x550")   # 父容器大小
        self.root.geometry(
            f"{str(width)}x{str(height)}+"+
            f"{int((self.root.winfo_screenwidth() - width) / 2)}+"+
            f"{int((self.root.winfo_screenheight() - height) / 2)}"
        )
        self.root.resizable(False, False)
        self.interface()

        print('开启第二个线程')
        thread2 = threading.Thread(target = handleBleData, daemon = True) # 新建线程用来不断接收数据并显示，与主线程并行
        thread2.start()# 开始线程
        option = tk.LabelFrame(self.root, text="SN和六位随机码", padx=10, pady=10)  # 水平，垂直方向上的边距均为10
        option.place(x=370, y=10, width=390)  # 坐标位置
        # 创建下拉列表
        ttk.Label(option, text="SN:").grid(column=0, row=0)  # 第0行第0列
        #ttk.Label(option, text="随机码:").grid(column=0, row=1) 

        global snVar
        global randomVar
        snVar = Entry(option)
        #randomVar = Entry(option)
        snVar.grid(row=0, column=1)
        #randomVar.grid(row=1, column=1)
        
    def interface(self):
        global Information_Window
        global Receive_Window
        #显示操作信息的框图
        Information = tk.LabelFrame(self.root, text="发送信息", padx=10, pady=10)  # 创建一个框架
        Information.place(x=10, y=340)                 #将该框架放在x=20，y=20的地方
        Information_Window = scrolledtext.ScrolledText(Information, width=40, height=8, padx=10, pady=10, wrap=tk.WORD)         #创建一个有滚动条的文本框
        Information_Window.grid()

        #接收文本框（带滚动条）
        Receive = tk.LabelFrame(self.root, text="测试结果", padx=10, pady=10)  # 水平，垂直方向上的边距均为 10
        Receive.place(x=10, y=10)
        Receive_Window = scrolledtext.ScrolledText(Receive, width=40, height=20, padx=10, pady=10, wrap=tk.WORD)
        Receive_Window.grid()
        
        # 创建按钮框图
        butt = tk.LabelFrame(self.root, text="按钮", padx=4, pady=5)  # 水平，垂直方向上的边距均为 10
        butt.place(x=370, y=100, width=390, height=400)
        tk.Button(butt, text="连接灯箱", command=checkStart,width=10).grid(row=0, column=0)
        tk.Button(butt, text="开始检测", command=checkRed,width=10).grid(row=1, column=0)
        #tk.Button(butt, text="绿色", command=checkGreen,width=10).grid(row=2, column=0)
        #tk.Button(butt, text="蓝色", command=checkBlue,width=10).grid(row=3, column=0)
        #tk.Button(butt, text="黑色", command=colseRGB,width=10).grid(row=4, column=0)
        #tk.Button(butt, text="打开", command=checkWhite,width=10).grid(row=5, column=0)
        #tk.Button(butt, text="关闭", command=closeLED,width=10).grid(row=6, column=0)
        tk.Button(butt, text="绑定SN码", command=bindingSN,width=20).grid(row=2, column=0)
        tk.Button(butt, text="查询设备SN码", command=getingSN,width=20).grid(row=2, column=1)
        tk.Button(butt, text="获取六位随机码", command=findRAND,width=20).grid(row=3, column=0)
        tk.Button(butt, text="绑定六位随机码", command=bindingRANDOM,width=20).grid(row=4, column=0)
        tk.Button(butt, text="查询设备六位随机码", command=getingRANDOM,width=20).grid(row=4, column=1)
        tk.Button(butt, text="上传结果", command=lambda: upload_result(snVar.get()),width=10).grid(row=5, column=0)
        tk.Button(butt, text="停止检测", command=checkEnd,width=10).grid(row=11, column=0)
        ttk.Label(butt, text="注意：点击停止检测后务必").grid(column=0, row=12)
        ttk.Label(butt, text="等待弹窗出现后进行其他操作").grid(column=1, row=12)
        #传输数据选项框图

        #建立端口号列

def bindingSN():
    # print('绑定SN')
    if bleConnected:
        # print('SN:', snVar.get())
        snV = snVar.get()

        if len(snV) == SN_LEN :
            # print('SN长度为:', len(snV))

            global setSNQue           
            global buttonActive

            bindSNLen = 0
            bindSNData = []
            bindSNData.append(0xAA)
            bindSNLen = bindSNLen + 1
            bindSNData.append(1)
            bindSNLen = bindSNLen + 1
            bindSNData.append(0x20)
            for v in snV:
                bindSNLen = bindSNLen + 1
                bindSNData.append(ord(v))
            
            bindSNData[1] = bindSNLen

            crcBuf = []
            for i in range(1, len(bindSNData)):
                crcBuf.append(bindSNData[i])

            crcData = calculate_crc16(crcBuf)
            bindSNLen = bindSNLen + 1
            crcL = crcData & 0xFF
            bindSNData.append(crcL)
            bindSNLen = bindSNLen + 1
            crcH = crcData >> 8
            bindSNData.append(crcH)


            # print("bindSNData=",bindSNData)
            # for v in bindSNData:
            #     print(hex(v))

            if buttonActive == ACTIVE_NONE:
                setSNQue.put(bytearray(bindSNData))
                buttonActive = ACTIVE_BINDING_SN_BUTTON


        else:
            # print('SN长度错误')
            messagebox.showwarning('提示', '请正确输入SN码')
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def bindingRANDOM():
    global randomV
    # print('绑定RANDOM')
    print("now random:", randomV)
    if bleConnected:
        #randomV = randomVar.get()

        if len(randomV) == 6:
            # print('六位随机码长度为:',len(randomV))

            global setSNQue           
            global buttonActive

            bindSNLen = 0
            bindSNData = []

            bindSNData.append(0xAA)
            bindSNLen = bindSNLen + 1
            bindSNData.append(1)
            bindSNLen = bindSNLen + 1
            bindSNData.append(0x21)
            
            for v in randomV:
                bindSNLen = bindSNLen + 1
                bindSNData.append(ord(v))

            bindSNData[1] = bindSNLen

            crcBuf = []
            for i in range(1, len(bindSNData)):
                crcBuf.append(bindSNData[i])

            crcData = calculate_crc16(crcBuf)

            bindSNLen = bindSNLen + 1
            crcL = crcData & 0xFF
            bindSNData.append(crcL)
            bindSNLen = bindSNLen + 1
            crcH = crcData >> 8
            bindSNData.append(crcH)

            # print("bind RANDOM Data=",bindSNData)
            # for v in bindSNData:
            #     print(hex(v))

            if buttonActive == ACTIVE_NONE:
                setSNQue.put(bytearray(bindSNData))
                buttonActive = ACTIVE_BINDING_RANDOM_BUTTON
        else:
            # print('RANDOM长度错误')
            messagebox.showwarning('提示', '请正确输入六位随机码')
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def getingSN():
    # print('获取SN')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_GET_SN_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def findRAND():
    global randomV
    snV = snVar.get()
    find_rand_url_final = find_rand_url + snV
    response = requests.request("GET", find_rand_url_final, headers=rand_headers, data=rand_payload)
    print(response.text)
    if json.loads(response.text)["resultCode"] == "OK":
        randomV = json.loads(response.text)["data"]["sn"]["rand"]
        messagebox.showinfo("6位随机码", "随机码为：" + randomV)
    else:
        print("Error:", json.loads(response.text)["resultDescription"])
        messagebox.showerror("错误提示", json.loads(response.text)["resultDescription"])
    print(randomV)

def findRAND_temp():
    global randomV
    snV = snVar.get()
    if sn_rand_pair.get(snV):
        randomV = sn_rand_pair[snV]
        print("fond_rand:", randomV)
        messagebox.showinfo("6位随机码", "随机码为：" + randomV)
    else:
        print("SN 不存在")
        messagebox.showerror("错误提示", "SN 不存在")

def getingRANDOM():
    # print('获取RANDOM')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_GET_RANDOM_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')


def checkRed():
    # print('检测红色')

    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_RED_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def checkGreen():
    # print('检测绿色')

    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_GREEN_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def checkBlue():
    # print('检测蓝色')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_BLUE_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def colseRGB():
    # print('关闭RGB')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_ALL_CLOSE_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def checkWhite():
    # print('检测白色')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_ON_BUTTON
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

def closeLED():
    # print('关闭LED')
    if bleConnected:
        global buttonActive
        if buttonActive == ACTIVE_NONE:
            buttonActive = ACTIVE_OFF_BUTTON 
    else:
        # print('请先连接蓝牙设备')
        messagebox.showwarning('提示', '请先连接蓝牙设备')

if __name__ == '__main__':
    if not os.path.exists(PRODUCT_RE_PATH):
        os.mkdir(PRODUCT_RE_PATH)
    gui = GUI()
    gui.root.mainloop()

